//
//  AccountModel.swift
//  App
//
//  Created by chenyh on 2018/5/28.
//


import Vapor
//import FluentSQLite
import FluentMySQL
import Crypto
import Random
let cipherKEY = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="

final class Account: MySQLModel {
    var id: Int?
    typealias Database = MySQLDatabase
    typealias ID = Int
    static let idKey: IDKey = \.id
    /// 用户ID
    var uid: String? = nil
    /// 用户名
    var username: String
    /// 用户密码
    var password: String? = nil
    /// 创建时间
    var create_at: String
    /// 最后一次登录时间
    var last_login: String
    /// 用户token
    var token: String? = nil
    /// 过期时间
    var expiredTime: String
    
    init(id: Int? = nil
        ,username: String
        ,password: String) {
        self.username = username

        //id加密
        if let digest = try? HMAC.SHA1.authenticate(username, key: UUID().description)  {
            //应该随机摘出几个
            self.uid = digest.hexEncodedString()
        }
        //密码加密
        if let digest = try? SHA1.hash(password) {
            self.password = digest.hexEncodedString(uppercase: true)
        }
        //第一次创建账号信息的时候 就会生成用户token
        self.create_at = "\(Int(Date().timeIntervalSince1970))"
        self.last_login = "\(Int(Date().timeIntervalSince1970))"
        self.expiredTime = "\(Int(Date().timeIntervalSince1970) + 30 * 24 * 60 * 60)"

        //有两个策略
        //1.将idSHA1加密 单向加密 token验证的时候 判断该token是否有效,
        //有效则查询到用户ID等信息,目的为了替代ID
        //无效则重新登录
        //2.使用BCrypt
        // 使用BCrypt对ID进行加密 生成token
        // 客户端根据请求的ID 查询TOKEN，如果Token存在 则使用BCrypt验证，通过则在当前会话中,
        // 否则会话失效
        //3. HMAC.SHA1.authenticate("vapor", key: "secret")
        
        //        if let digest = try? BCrypt.hash(self.id!, cost: 4) {
        //            self.token = digest
        //        }
        //
        //        if let result = try? BCrypt.verify(self.id!, created: self.token) {
        //
        //        }
        if let digest = try? SHA1.hash(self.uid!) {
            print(digest.hexEncodedString())
            self.token = digest.hexEncodedString(uppercase: true)
        }

    }
   
    
    public static func userExist(req: Request,token: String) throws -> Future<Account?> {
        return try Account.query(on: req).filter(\.token  == token).first()
    }
    
    public static func userExist(req: Request,rusername: String) throws -> Future<Account?> {
        return try Account.query(on: req).filter(\.username  == rusername).first()
    }
    
    public static func login(req: Request,
                       rusername: String,
                       rpassword: String)
                       throws -> Future<Account?> {
        return try Account
            .query(on: req)
            .filter(\.username  == rusername)
            .filter(\.password  == rpassword).first()
        
    }


}


/// Allows `Todo` to be used as a dynamic migration.
extension Account: Migration { }

/// Allows `Todo` to be encoded to and decoded from HTTP messages.
extension Account: Content { }

/// Allows `Todo` to be used as a dynamic parameter in route definitions.
extension Account: Parameter { }

